﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Collections.Generic;
using System.IO;

/// <summary>
///PublicClass 的摘要说明
/// </summary>
namespace LTP.Common
{
    public class FileClass
    {
        public FileClass()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }



        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileUpload">上传控件</param>
        /// <param name="fileType">上传文件后缀</param>
        /// <param name="savePath">保存目录</param>
        /// <param name="maxSize">文件最大值(KB)</param>
        /// <param name="fileName">保存文件名</param>
        /// <returns></returns>
        public static string UploadFile(FileUpload fileUpload, string fileType, string savePath, int maxSize, ref string fileName)
        {
            StringBuilder errorString = new StringBuilder();
            if (fileUpload.HasFile)
            {
                string pathname = fileUpload.PostedFile.FileName;  //上传文件客户端路径完整名称
                int fileSize = fileUpload.PostedFile.ContentLength; //上传文件大小 B为单位
                string filetp = System.IO.Path.GetExtension(pathname).ToLower();  //上传文件后缀

                if (fileType.ToLower().IndexOf(filetp.ToLower()) > -1)
                {
                    if (fileSize <= maxSize)
                    {
                        string filePath = System.Web.HttpContext.Current.Server.MapPath(savePath);

                        string sFolder = DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString();//根据日期生成文件夹
                        filePath = filePath + sFolder + @"/";

                        if (!Directory.Exists(filePath)) //如果路径不存在，则创建
                            Directory.CreateDirectory(filePath);

                        Random ra = new Random();
                        string NewfileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ra.Next(10, 99).ToString() + filetp.ToString(); //上传后文件名称！ 

                        if (!File.Exists(filePath + NewfileName))
                        {
                            try
                            {
                                fileUpload.SaveAs(filePath + NewfileName);
                                if (!String.IsNullOrEmpty(fileName))
                                {
                                    DelFile(@"~/" + fileName);
                                }
                                fileName = savePath + sFolder + @"/" + NewfileName;
                            }
                            catch
                            {
                                errorString.Append("文件上传失败！");
                            }
                        }
                        else
                        {
                            errorString.Append("上传失败，目录下存在同名文件！");
                        }
                    }
                    else
                    {
                        errorString.Append("文件不能大于" + maxSize.ToString() + "KB");
                    }
                }
                else
                {
                    errorString.Append("文件类型错误，文件类型应为" + fileType);
                }
            }
            else
            {
                errorString.Append("错误：上传文件不存在！");

            }

            return errorString.ToString();
        }


        /// <summary>
        /// 同时上传两个文件
        /// </summary>
        /// <param name="fileUpload">上传控件</param>
        /// <param name="fileType">上传文件后缀</param>
        /// <param name="savePath">保存目录</param>
        /// <param name="maxSize">文件最大值(KB)</param>
        /// <param name="fileName">保存文件名</param>
        /// <returns></returns>
        public static string UploadFile2(FileUpload fileUpload, string fileType, string savePath, int maxSize, ref string fileName,int NUM)
        {
            StringBuilder errorString = new StringBuilder();
            if (fileUpload.HasFile)
            {
                string pathname = fileUpload.PostedFile.FileName;  //上传文件客户端路径完整名称
                int fileSize = fileUpload.PostedFile.ContentLength; //上传文件大小 B为单位
                string filetp = System.IO.Path.GetExtension(pathname).ToLower();  //上传文件后缀

                if (fileType.ToLower().IndexOf(filetp.ToLower()) > -1)
                {
                    if (fileSize <= maxSize)
                    {
                        string filePath = System.Web.HttpContext.Current.Server.MapPath(savePath);

                        string sFolder = DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString();//根据日期生成文件夹
                        filePath = filePath + sFolder + @"/";

                        if (!Directory.Exists(filePath)) //如果路径不存在，则创建
                            Directory.CreateDirectory(filePath);

                        Random ra = new Random();
                        string NewfileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ra.Next(10, 99).ToString() + NUM.ToString() + filetp.ToString(); //上传后文件名称！ 

                        if (!File.Exists(filePath + NewfileName))
                        {
                            try
                            {
                                fileUpload.SaveAs(filePath + NewfileName);
                                if (!String.IsNullOrEmpty(fileName))
                                {
                                    DelFile(@"~/" + fileName);
                                }
                                fileName = savePath + sFolder + @"/" + NewfileName;
                            }
                            catch
                            {
                                errorString.Append("文件上传失败！");
                            }
                        }
                        else
                        {
                            errorString.Append("上传失败，目录下存在同名文件！");
                        }
                    }
                    else
                    {
                        errorString.Append("文件不能大于" + maxSize.ToString() + "KB");
                    }
                }
                else
                {
                    errorString.Append("文件类型错误，文件类型应为" + fileType);
                }
            }
            else
            {
                errorString.Append("错误：上传文件不存在！");

            }

            return errorString.ToString();
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件保存路径</param>
        /// <returns></returns>
        public static string DelFile(string filePath)
        {
            string FPath = System.Web.HttpContext.Current.Server.MapPath(filePath);
            string error = "";
            try
            {
                if (File.Exists(FPath))
                    File.Delete(FPath);
            }
            catch (Exception ex)
            {
                error = "删除文件失败：" + ex.ToString();
            }
            return error;
        }

        /// <summary>
        /// 转换文件
        /// </summary>
        /// <param name="wordPath"></param>
        /// <returns></returns>
        public static bool Convert(string wordPath)
        {
            try
            {
                PDFConverter pdfConverter = new PDFConverter();
                SWFConverter swfConverter = new SWFConverter();
                string pdfFile = wordPath.Substring(0, wordPath.LastIndexOf('.')) + "_PDF.pdf";
                string swfFile = wordPath.Substring(0, wordPath.LastIndexOf('.')) + "_SWF.swf";
                if (File.Exists(pdfFile))
                    File.Delete(pdfFile);
                if (File.Exists(swfFile))
                    File.Delete(swfFile);
                pdfConverter.Convert(wordPath, pdfFile);
                if (string.IsNullOrEmpty(pdfConverter.errormessage))
                {
                    if (File.Exists(pdfFile))
                    {
                        swfConverter.Convert(pdfFile, swfFile);
                        return true;
                    }
                    else
                    {
                        throw new Exception("无法找到PDF文件");
                    }
                }
                else
                {
                    throw new Exception("无法找到Word文件");
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="strPath"></param>
        public static void DownloadFile(string strPath)
        {
            System.IO.FileInfo file = new System.IO.FileInfo(strPath);
            if (file.Exists)
            {
                string ss = HttpUtility.UrlEncode(strPath.Substring(strPath.LastIndexOf("/") + 1), System.Text.Encoding.UTF8);
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(strPath.Substring(strPath.LastIndexOf("/") + 1), System.Text.Encoding.UTF8));
                System.Web.HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
                System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                System.Web.HttpContext.Current.Response.Filter.Close();
                System.Web.HttpContext.Current.Response.WriteFile(file.FullName);
                System.Web.HttpContext.Current.Response.End();
            }
        }
    }
}